import json
import re

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.users.models import User, Address
from apps.users.utils import generate_verify_token, check_verify_token
from celery_tasks.email.tasks import send_verify_mail
from utils.viewmixin import LoginMixin


class UsernameCountView(View):
    """
    判断用户名是否重复
    前端  ：用户 输入用户名后 ，失去了焦点 ，发送一个axios（ajax）请求
    后端 :
        接受请求 ：接受用户名

        路由:get   /usernames/<username>/count/

        业务逻辑： 根据用户名 查询数据库 ，查询当前数量， 数量大于0说明已经注册过了
        响应 JSON格式
        {"count": 1, "code": "0", "errmsg": "OK"}

    """

    def get(self, request, username):
        # 1 接受用户名
        print(username)
        # 2 根据用户名查数据库
        count = User.objects.filter(username=username).count()
        # 3 返回响应
        return JsonResponse({"count": "count", "code": "0", "errmsg": "ok"})


class RegisterView(View):
    """
    注册
    前端  ：用户 输入用户名，密码 确认密码 手机号 同意协议，点击注册按钮，发送axios请求
    后端 :
        接受请求 ：接受JSON 数据

        路由:post '/register/'

        业务逻辑： 验证数据 保存到数据库
        响应 JSON格式
        {"code": "0", "errmsg": "OK"}
        {"code": "400", "errmsg": "register fail"}

    """

    def post(self, request):
        # 1 接受请求
        body_byte = request.body
        # 获取json格式数据 转为字典
        body_dict = json.loads(body_byte)

        # 2 获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3 验证数据
        # 3.1 验证是否为空
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": 400, "errmsg": "register fail"})
        # 3.2 正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": 400, "errmsg": "register fail"})
        try:
            # 4 生成用户保存到数据库
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "用户保存失败 检查用户信息"})

        # 短信验证码验证
        # 从redis里获取短信验证码
        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)
        # 判断是否过期
        if redis_sms_code is None:
            return JsonResponse({"code": 400, "errmsg": "短信验证码过期"})
        if redis_sms_code.decode().lower() != sms_code.lower():
            return JsonResponse({"code": 400, "errmsg": "短信验证码错误"})
        login(request, user)
        # 5 返回响应
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)
        merge_cart_cookie_to_redis(request, user, response)
        # # 5返回响应（json数据）
        return response


class LoginView(View):
    """
    注册
    前端  ：用户 输入用户名，密码 勾选是否记住用户  点击登录按钮  发送axios请求
    后端 :
        接受请求 ：接受JSON 数据 验证数据

        路由:post '/login/'

        业务逻辑： 验证数据  验证用户名和密码是否正确   状态保持
        响应 JSON格式
        {"code": "0", "errmsg": "OK"}
        {"code": "400", "errmsg": "login fail"}
    """

    def post(self, request):
        # 1 接收数据
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")
        # 2 验证数据
        if not all([username, password]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})
        # 3 验证用户名密码
        if re.match(r'1[3-9]\d{9}', username):
            User.USERNAME_FIELD = "mobile"
        else:
            User.USERNAME_FIELD = "username"
        try:
            user = authenticate(username=username, password=password)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "登录失败"})
        if not user:
            return JsonResponse({"code": 400, "errmsg": "用户名或密码错误"})
        # 4 状态保持
        login(request, user)
        # 5 判断是否记住登录 设置session有效期
        if remembered:
            # 记住登录
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        # 6 返回响应
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.set_cookie("username", user.username, max_age=3600 * 24 * 5)
        merge_cart_cookie_to_redis(request, user, response)
        return response


class LogoutView(View):
    """
    注册
    前端  ：用户 在首页点击退出 发送一个axios请求
    后端 :
        路由:delete 'http://www.meiduo.site:8000/logout/'

        业务逻辑： 清空session 和cookie 返回响应
        响应 JSON格式
        {"code": "0", "errmsg": "OK"}
        {"code": "400", "errmsg": "login fail"}
    """

    def delete(self, request):
        # 1 调用logout清空状态保持的session
        logout(request)

        # 2 删除cookie里的username
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.delete_cookie("username")

        # 3 返回响应
        return response


class UserInfoView(LoginMixin, View):
    def get(self, request):
        user = request.user
        return JsonResponse({
            "code": 0,
            "errmsg": "个人中心",
            "info_data": {
                "username": user.username,
                "mobile": user.mobile,
                "email": user.email,
                "email_active": user.email_active
            }
        })


class SaveEmailView(LoginMixin, View):
    """
    前端  点击设置 输入邮箱地址 点击保存 发送请求

    后端
        接受请求  邮箱的地址
        逻辑  保存邮箱地址到用户信息里，发送一封激活邮件
        响应 json数据
        路由 /emails/
        请求方式 put
    """

    def put(self, request):
        # 1 获取数据
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get("email")
        # 校验数据
        if not email:
            return JsonResponse({"code": 400, "errmsg": "邮箱地址格式错误"})
        # 2 保存邮箱地址
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "邮箱保存失败"})
        # 3 发送邮件
        print("发送邮件")
        subject = "美多商城验证邮箱"
        recipient_list = [email]
        token = generate_verify_token(request.user.id)
        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        html_message = '<p>尊敬的用户您好!</p>' \
                       '<p>感谢您使用美多商城<p>' \
                       '<p>您的邮箱为:%s。请点击此链接激活您的邮箱:</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)
        # 4 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok"})


class EmailVerifyView(View):
    """
    前端发送
    用户点击邮箱里的激活链接 发送 /emails/verification/？token=xxx 请求

    后端：
        接受请求 获取参数 验证
        逻辑 解密token得到user_id 根据user_id去数据库查询 数据 修改邮箱激活字段
        返回响应

    路由  put  /emails/verification/？token=xxx前端发送
    用户点击邮箱里的激活链接 发送 /emails/verification/？token=xxx 请求

    后端：
        接受请求 获取参数 验证
        逻辑 解密token得到user_id 根据user_id去数据库查询 数据 修改邮箱激活字段
        返回响应

    路由  put  /emails/verification/？token=xxx
    """

    def put(self, request):
        # 1 获取参数
        token = request.GET.get("token")
        # 2 校验参数
        if token is None:
            return JsonResponse({"code": 400, "errmsg": "缺少token"})
        # 3 解密获取user_id
        user_id = check_verify_token(token)
        # 4 判断user_id是否为空
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})
        try:
            # 5 查询用户
            user = User.objects.get(id=user_id)
            # 6 修改用户邮箱激活字段为True
            user.email_active = True
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查询不到用户"})
        # 7 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok"})


class AddressCreateView(LoginMixin, View):
    """
    需求  增加一个收货地址
    前端    用户填写完收货地址 点击保存  发送一个axios请求    把数据传过来

    后端

    请求  接受请求 获取和验证参数
    逻辑  把数据保存到数据库
    返回响应

    路由  POST  /addresses/create/

    {'code':0,"errmsg":"ok","address":{"title":"老家地址","mobile":"1551234431",,,,}}
    """

    def post(self, request):
        # 1 接受请求
        body = request.body
        data_dict = json.loads(body)
        # 2 获取参数
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")
        # 3 验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({"code": 400, "errmsg": "参数不全"})
        # 正则验证手机号和邮箱
        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({"code": 400, "errmsg": "手机号格式不对"})
        if email:
            if not re.match(r"^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
                return JsonResponse({"code": 400, "errmsg": "邮箱格式不对"})

        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "保存数据失败"})
        # 数据转为字典
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 5返回响应
        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})


class AddressView(LoginMixin, View):
    def get(self, request):
        # 1 获取用户对象
        user = request.user
        # 2 查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=user, is_deleted=False)
        # 3 转为字典数据
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 4 返回
        return JsonResponse({"code": 0, "errmsg": "ok", "addresses": addresses_list})
